//
//  LoginPanel.m
//  Dolphin
//
//  Created by Matthew on 11-10-11.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "LoginPanel.h"
#import "UtilClass.h"
#define LOGIN_WEB_SERVICE @"http://my.zhulong.com/sso/msignin.asp"
#define SLIDE_HEIGHT 200
@implementation LoginPanel

@synthesize userName;
@synthesize userPass;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Initialization code
        
        self.backgroundColor = [UIColor whiteColor];

        loginPanelHolder = [[UIView alloc] initWithFrame:CGRectMake(0, -30, 320, 480)];
        loginPanelHolder.transform = CGAffineTransformMakeTranslation(0,0);
        [self addSubview:loginPanelHolder];
        
        UILabel *usrNameText = [[UILabel alloc] initWithFrame:CGRectMake(20, 66-113, 560, 250)];
        usrNameText.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:18];
        usrNameText.numberOfLines = 0;
        [usrNameText setBackgroundColor:[UIColor clearColor]];
        //[usrNameText setTextColor:[ColorUtil stringHexToUIColor:@"0x37445f"]];
        usrNameText.textAlignment = UITextAlignmentLeft;
        [usrNameText setText:@"帐号:"];
        [loginPanelHolder addSubview:usrNameText];
        
        UILabel *usrPassText = [[UILabel alloc] initWithFrame:CGRectMake(20, 114-113, 560, 250)];
        usrPassText.font = [UIFont fontWithName:@"STHeitiSC-Medium" size:18];
        usrPassText.numberOfLines = 0;
        [usrPassText setBackgroundColor:[UIColor clearColor]];
        //[usrPassText setTextColor:[ColorUtil stringHexToUIColor:@"0x37445f"]];
        usrPassText.textAlignment = UITextAlignmentLeft;
        [usrPassText setText:@"密码:"];
        [loginPanelHolder addSubview:usrPassText];
        
        userNameTextField = [[UITextField alloc] initWithFrame:CGRectMake(80,66,220, 25)];
        userNameTextField.borderStyle = UITextBorderStyleNone;

        userNameTextField.font = [UIFont systemFontOfSize:18.0];  //font size
        userNameTextField.placeholder = @"用户帐号";  //place holder
        userNameTextField.backgroundColor = [UIColor clearColor]; //background color
        userNameTextField.autocorrectionType = UITextAutocorrectionTypeNo;	// no auto correction support
        
        userNameTextField.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
        userNameTextField.returnKeyType = UIReturnKeyDone;  // type of the return key

        userNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
        
        //textFieldRounded.delegate = self.view;	// let us be the delegate so we know when the keyboard's "Done" button is pressed
        [loginPanelHolder addSubview:userNameTextField];

        userPassTextField = [[UITextField alloc] initWithFrame:CGRectMake(80,114,220, 25)];
        userPassTextField.borderStyle = UITextBorderStyleNone;
        
        userPassTextField.font = [UIFont systemFontOfSize:18.0];  //font size
        userPassTextField.placeholder = @"输入密码";  //place holder
        userPassTextField.backgroundColor = [UIColor clearColor]; //background color
        userPassTextField.autocorrectionType = UITextAutocorrectionTypeNo;	// no auto correction support
        userPassTextField.secureTextEntry = TRUE;
        userPassTextField.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
        userPassTextField.returnKeyType = UIReturnKeyDone;  // type of the return key
        
        userPassTextField.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
        
        //textFieldRounded.delegate = self.view;	// let us be the delegate so we know when the keyboard's "Done" button is pressed
        [loginPanelHolder addSubview:userPassTextField];       
        
        loginBtn = [[ImageUIButton alloc] initWithFrame:CGRectMake(170,-3, 104, 40)];
        [loginBtn  setImage:[UIImage imageNamed:@"login_button.png"] forState:UIControlStateNormal];
        [loginBtn  setImage:[UIImage imageNamed:@"login_button.png"] forState:UIControlStateSelected];
        [loginBtn  addTarget:self action:@selector(mouseDownProc:) forControlEvents:UIControlEventTouchDown];
        [loginBtn setXY:200 offy:145];
        loginBtn.button_id = 10;
        [loginPanelHolder addSubview:loginBtn];
        
    }
    return self;
}

-(void) mouseDownProc:(id)sender
{
    [userNameTextField resignFirstResponder];
    [userPassTextField resignFirstResponder];
    
    userName = userNameTextField.text;
    
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"YYYY-M-dd HH:mm:00"];
    NSString *timeData = [dateFormat stringFromDate:date];  
    [dateFormat release];
    
   NSLog(@"timeData:%@",timeData);
    
    NSString *mdSeed = [[NSString alloc] initWithFormat:@"zlw%@%@",userNameTextField.text,timeData];
    NSString *md5str = [UtilClass md5FromString: mdSeed];
    NSString *readyStr = [[NSString alloc] initWithFormat:@"%@$%@",timeData,md5str];
    NSString *secret_str = [UtilClass Base64EncodeString:readyStr];
    
    NSString *utf8QueryStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                                                 NULL,
                                                                                 (CFStringRef)secret_str,
                                                                                 NULL,
                                                                                 (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                 kCFStringEncodingUTF8 );

    NSString *urlStr = [[NSString alloc] initWithFormat: 
                        @"%@?ln=%@&lp=%@&s=%@",
                        LOGIN_WEB_SERVICE,userNameTextField.text,userPassTextField.text,utf8QueryStr];
    
    NSLog(@"url link%@",urlStr);
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url 
                                                  cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
    NSURLConnection *_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self
                                                           startImmediately:YES];
    [request release];
    [_connection release];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"login_start" object:self];
}

-(void) active
{
    [UIView transitionWithView:self duration:0.5f 
                       options:UIViewAnimationCurveEaseOut  animations:
     ^{
         loginPanelHolder.transform = CGAffineTransformMakeTranslation(0,0);
         self.alpha = 1.0f;
     }
                    completion:NULL];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSString* aStr;
	aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    if([aStr rangeOfString: @"<status>1<" options: NSCaseInsensitiveSearch].location != NSNotFound)
    {
        NSLog(@"login success");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"login_success" object:self];
    }
    else
    {
        UIAlertView *av= [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"登陆失败，请检查你的帐户或密码是否输入正确"delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
        [av show];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"login_fail" object:self];

    }

    [aStr release];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)dealloc
{
    [super dealloc];
}

@end
